package svc

import (
	accountmodel "googee/service/account/model"
	"googee/service/account/rpc/account"
	"googee/service/admin/api/internal/config"
	"googee/service/admin/api/internal/middleware"
	"googee/service/admin/rpc/sys"
	leaderboardmodel "googee/service/leaderboard/model"
	"googee/service/user/model"
	"googee/service/user/rpc/user"

	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
	Config           config.Config
	CheckUrl         rest.Middleware
	Sys              sys.Sys
	Redis            *redis.Redis
	UserModel        model.UserModel
	User             user.User
	Account          account.Account
	AccountModel     accountmodel.AccountModel
	AccountLogModel  accountmodel.AccountLogModel
	LeaderboardModel leaderboardmodel.LeaderboardsModel
}

func NewServiceContext(c config.Config) *ServiceContext {
	newRedis := redis.New(c.Redis.Address, redisConfig(c))
	conn := sqlx.NewMysql(c.Mysql.DataSource)
	sys := sys.NewSys(zrpc.MustNewClient(c.Sys))
	return &ServiceContext{
		Config:           c,
		CheckUrl:         middleware.NewCheckUrlMiddleware(newRedis, sys, c.Mode).Handle,
		Sys:              sys,
		Redis:            newRedis,
		UserModel:        model.NewUserModel(conn, c.CacheRedis),
		AccountModel:     accountmodel.NewAccountModel(conn, c.CacheRedis),
		AccountLogModel:  accountmodel.NewAccountLogModel(conn, c.CacheRedis),
		User:             user.NewUser(zrpc.MustNewClient(c.User)),
		Account:          account.NewAccount(zrpc.MustNewClient(c.Account)),
		LeaderboardModel: leaderboardmodel.NewLeaderboardsModel(conn, c.CacheRedis),
	}
}

func redisConfig(c config.Config) redis.Option {
	return func(r *redis.Redis) {
		r.Type = redis.NodeType
		r.Pass = c.Redis.Pass
	}
}
